// 登录页面的路由守卫

import {FC, useEffect} from "react"
import { useRoutes,useNavigate,useLocation }  from "react-router-dom"
import useStorage from "./useStorage"

interface Iprops{
    routes:Object[];
    tokenKey:string
}
// 从App.tsx获取到的props
const useRouteWithGuard:FC<Iprops>=(props)=>{
    let {routes,tokenKey}=props

    let [tokenvalue,methods]=useStorage(tokenKey)
    // 当前访问的路径
    let location=useLocation()
    // 编程式导航
    let navigate=useNavigate()
    
    useEffect(()=>{
        if(!tokenvalue){
            // 如果没有token
            if(location.pathname!=="/login"){
                navigate("/login")
            }
        }
    },[location])


    let element=useRoutes(routes)
    return element
}
export default useRouteWithGuard
